package com.systop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.systop.domain.to.OrderTo;
import com.systop.domain.vo.GoodsSalesVo;
import com.systop.domain.vo.OrderConfirmVo;
import com.systop.domain.vo.OrderSubmitResponseVo;
import com.systop.domain.vo.OrderSubmitVo;
import com.systop.domain.vo.SumSalesVo;
import com.systop.entity.Consignee;
import com.systop.entity.Goods;
import com.systop.entity.Order;
import com.systop.entity.SysUser;
import com.systop.service.ConsigneeService;
import com.systop.service.OrderService;
import com.systop.service.SysUserService;
import com.systop.utils.BizCodeEnum;
import com.systop.utils.R;
import lombok.Getter;
import org.aspectj.weaver.ast.Var;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/OrderManage")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    AmqpTemplate amqpTemplate;

    @RequestMapping(value = "/findAllOrders",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> findAllOrders(@RequestParam Map<String,Object> map){
        //将JSON数据转换成java能识别的对象类数据
        Order order =
                JSON.parseObject(JSON.parse(JSON.toJSONString(map.get("order"))).toString(),
                        new TypeReference<Order>(){});
        //输出返回值数据
        System.out.println(order);
        //查询所有用户名,返回到下拉框
        List<SysUser> sysUsersList = orderService.findAllUser();
        map.put("sysUsersList",sysUsersList);
        //查询所有收货人，前台根据相关用户名显示对应收货人
        List<Consignee> consigneesList = orderService.findAllConsignee();
        map.put("consigneesList",consigneesList);
        //查询所有商品
        List<Goods> goodsList = orderService.findAllGoods();
        map.put("goodsList",goodsList);

        //查询符合条件的订单总数
        int pageCount = orderService.countOrders(order);
        map.put("pageCount",pageCount);
        //计算分页起始
        order.setStart((order.getStart()-1)*order.getPageSize());
        //查询订单数据
        List<Order> list = orderService.findAllOrders(order);
        //处理当前页面空值
        if(CollectionUtils.isEmpty(list) && order.getStart()>0){
            //设置当本页没有数据时返回上一页
            order.setStart(order.getStart()/order.getPageSize());
            map.put("order", order);
            return findAllOrders(map);
        }
        map.put("orderList",list);
        return map;
    }

    //查询个人所有订单
    @RequestMapping(value = "/queryMyOrderList",method = RequestMethod.GET)
    @ResponseBody
    public R queryMyOrderList(@RequestParam String userCode){
        System.out.println(userCode);

        if(userCode == null || userCode == "")
            return R.error();

        //查询用户信息
        SysUser user = sysUserService.findUserByUserCode(userCode);
        if (user == null)
            return R.error("用户不存在");

        List<OrderTo> orderTos = new ArrayList<>();
        try {
            orderTos = orderService.queryMyOrderList(user);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return R.ok().put("orderList",orderTos);
    }


    @RequestMapping(value = "/addOrder",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> addOrder(@RequestBody Map<String,Object> map){
        // Map<String,Object> map = new HashMap<>();
        //将JSON数据转换成java能识别的对象类数据
        Order order =
                JSON.parseObject(
                        JSON.parse(
                                JSON.toJSONString(map.get("order"))).toString(),
                new TypeReference<Order>(){});
        System.out.println(order);
        //查询商品单价和规格
        Goods goods = orderService.findPriceById(order);
        if(goods.getPrice()!=0||goods.getSpecification()!=0){
            //设置总价=单价*(数量/规格)
            order.setSumPrice(goods.getPrice()*(order.getGoodsNum()/ goods.getSpecification()));
            System.out.println(order.getSumPrice());
            //添加订单
            int i = orderService.addOrder(order);
            map.put("udpSuccNum",i);
            if(i>0){
                map.put("msg", "添加成功!");
            }else{
                map.put("msg","添加失败,订单不存在");
            }
        }
        return map;
    }

    @RequestMapping(value = "/delOrder",method = RequestMethod.DELETE)
    @ResponseBody
    //删除订单
    public Map<String,Object> delOrder(Order order){
        Map<String,Object> map = new HashMap<>();
        int i = orderService.delOrder(order);
        map.put("delSuccNum",i);
        if(i>0){
            map.put("msg", "删除成功!");
        }else{
            map.put("msg","删除失败,用户不存在");
        }
        return map;
    }


    //订单确认页数据渲染
    @RequestMapping(value = "/confirmOrder",method = RequestMethod.POST)
    @ResponseBody
    public R confirmOrder(){
        OrderConfirmVo confirmVo = null;
        try {
            confirmVo = orderService.confirmOrder();
        } catch (ExecutionException e) {
            e.printStackTrace();
            return R.error("出错了");
        } catch (InterruptedException e) {
            e.printStackTrace();
            return R.error("出错了");
        }
        return R.ok().put("confirmVo",confirmVo);
    }

    /**
     * 提交订单方法
     * @return
     */
    @RequestMapping(value = "/submitOrder",method = RequestMethod.POST)
    @ResponseBody
    public R submitOrder(@RequestBody OrderSubmitVo orderSubmitVo){

        System.out.println(orderSubmitVo);

        OrderSubmitResponseVo vo = orderService.submitOrder(orderSubmitVo);

        //下单失败处理
        if (vo.getOrderList()==null || vo.getOrderList().size() == 0) {
            String msg = "下单失败:";
            switch (vo.getCode()){
                case 10150 : msg += BizCodeEnum.TOKEN_VERIFY.getMsg();
                case 10151 : msg += BizCodeEnum.AMOUNT_COMPARISON_FAILED.getMsg();
                case 10152 : msg += BizCodeEnum.STOCK_LOCK_FAIL.getMsg();
            }
            return R.error(msg);
        }
        return R.ok().put("orderSn", vo.getOrderList().get(0).getOrderNo());
    }

    /**
     *
     *
     * 数据统计相关controller
     *
     *
     */

    /**
     *
     * @param year 查询month年的收入情况
     * @param month 查询month月的收入情况
     * @return
     */
    @GetMapping("/querySalesGroupByMonth")
    @ResponseBody
    public R querySalesGroupByMonth(@RequestParam(value = "year",required = false) String year,
                                    @RequestParam(value = "month",required = false) String month){
        //如果year为空，默认将今年作为默认值
        if(year == null || year.equals("")){
            year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            // System.out.println("今年是"+year+"年");
        }
        //单位数月份补0
        if(month !=null && month.length()==1){
            month = "0"+month;
        }
        List<SumSalesVo> sumSalesList = orderService.querySalesGroupByMonth(year,month);
        return R.ok().put("sumSalesList", sumSalesList);
    }

    /**
     * 查询具体时间商品销售详细情况
     * @param year
     * @param month
     * @return
     */
    @GetMapping("/querySalesDetail")
    @ResponseBody
    public R querySalesDetail(@RequestParam(value = "year",required = false) String year,
                              @RequestParam(value = "month",required = false) String month){
        System.out.println(Calendar.getInstance());

        //如果year为空，默认将今年作为默认值
        if(year == null || year.equals("")){
            year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            System.out.println("今年是"+year+"年");
        }
        //如果month为空，默认将当月作为默认值
        if(month == null || month.equals("")){
            month = String.valueOf(Calendar.getInstance().get(Calendar.MONTH)+1);
            //单位数月份补0
            if(month.length()==1)
                month = "0"+month;
        }
        List<GoodsSalesVo> goodsSalesList = orderService.querySalesDetail(year,month);
        return R.ok().put("goodsSalesList",goodsSalesList);
    }
}
